package com.zky.gulimall.ware.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zky.common.exception.NoStockException;
import com.zky.common.to.SkuHasStockVo;
import com.zky.common.to.mq.OrderTo;
import com.zky.common.to.mq.StockDetailLockedTo;
import com.zky.common.to.mq.StockLockedTo;
import com.zky.common.utils.R;
import com.zky.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.zky.gulimall.ware.entity.WareOrderTaskEntity;
import com.zky.gulimall.ware.feign.OrderFeignService;
import com.zky.gulimall.ware.feign.ProductFeignService;
import com.zky.gulimall.ware.service.WareOrderTaskDetailService;
import com.zky.gulimall.ware.service.WareOrderTaskService;
import com.zky.gulimall.ware.vo.OrderItemVo;
import com.zky.gulimall.ware.vo.OrderVo;
import com.zky.gulimall.ware.vo.SkuWareHasStock;
import com.zky.gulimall.ware.vo.WareSkuLockVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zky.common.utils.PageUtils;
import com.zky.common.utils.Query;

import com.zky.gulimall.ware.dao.WareSkuDao;
import com.zky.gulimall.ware.entity.WareSkuEntity;
import com.zky.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
@Slf4j
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private WareOrderTaskService wareOrderTaskService;
    @Autowired
    private WareOrderTaskDetailService taskDetailService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        Object skuId = params.get("skuId");
        if (Objects.nonNull(skuId)) {
            String skuId1 = (String) skuId;
            if (!"0".equalsIgnoreCase(skuId1) && !StringUtils.isEmpty(skuId1)) {
                queryWrapper.eq("sku_id", skuId1);
            }
        }

        Object wareId = params.get("wareId");
        if (Objects.nonNull(wareId)) {
            String wareId1 = (String) wareId;
            if (!"0".equalsIgnoreCase(wareId1) && !StringUtils.isEmpty(wareId1)) {
                queryWrapper.eq("ware_id", wareId1);
            }
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //若是还没有库存信息
        List<WareSkuEntity> skuEntities = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (CollectionUtils.isEmpty(skuEntities)) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStock(0);
            try {
                R info = productFeignService.info(skuId);
                if (info.isSuccess()) {
                    Map<String, Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                    wareSkuEntity.setSkuName(String.valueOf(skuInfo.get("skuName")));
                }
            } catch (Exception e) {
                log.error("productFeignService info", e);
            }

            this.baseMapper.insert(wareSkuEntity);
        } else {
            this.baseMapper.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        if (CollectionUtils.isEmpty(skuIds)) {
            log.warn("skuIds is null");
            return null;
        }
        List<SkuHasStockVo> stockVoList = skuIds.stream().map(item -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            Long count = baseMapper.getSkuStock(item);
            skuHasStockVo.setSkuId(item);
            if (count == null) {
                skuHasStockVo.setHasStock(false);
            } else {
                skuHasStockVo.setHasStock(count > 0);
            }
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return stockVoList;
    }

    //默认运行时异常全部回滚
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo lockVo) {
        log.warn("orderLockStock,lockVo:{}", lockVo);
        //保存库存工作单
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(lockVo.getOrderSn());
        wareOrderTaskService.save(taskEntity);

        //找到每个商品在哪个库存
        List<OrderItemVo> locks = lockVo.getLocks();
        if (CollectionUtils.isEmpty(locks)) {
            return null;
        }
        List<SkuWareHasStock> hasStockList = locks.stream().map(e -> {
            SkuWareHasStock hasStock = new SkuWareHasStock();
            Long skuId = e.getSkuId();
            hasStock.setSkuId(skuId);
            hasStock.setNum(e.getCount());
            //查询这个方法在哪里有库存
            List<Long> wareIds = baseMapper.listWareIdHasSkuStock(skuId);
            hasStock.setWareId(wareIds);
            return hasStock;
        }).collect(Collectors.toList());

        //锁定库存
        for (SkuWareHasStock stock : hasStockList) {
            Boolean skuLock = false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            if (CollectionUtils.isEmpty(wareIds)) {
                throw new NoStockException(skuId);
            }
            //1 如果每个商品都锁定成功，将当前商品锁定几件的工作单记录发给mq
            //2 锁定失败，前面保存的工作单回滚
            for (Long wareId : wareIds) {
                log.warn("开始锁定库存,skuId:{},wareId:{},num:{}", skuId, wareId, stock.getNum());
                //成功就返回1，否则返回0
                Long count = baseMapper.lockSkuStock(skuId, wareId, stock.getNum());
                if (count == 1) {
                    //锁定成功
                    skuLock = true;
                    log.warn("锁定库存成功,skuId:{},wareId:{},num:{}", skuId, wareId, stock.getNum());
                    //保存库存工作单详情
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
                    detailEntity.setSkuId(skuId);
                    detailEntity.setSkuNum(stock.getNum());
                    detailEntity.setTaskId(taskEntity.getId());
                    detailEntity.setWareId(wareId);
                    detailEntity.setLockStatus(1);
                    taskDetailService.save(detailEntity);
                    //告诉mq锁定成功
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());
                    StockDetailLockedTo detailLockedTo = new StockDetailLockedTo();
                    BeanUtils.copyProperties(detailEntity, detailLockedTo);
                    //发送详情，防止回滚后找不到数据
                    lockedTo.setDetail(detailLockedTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", lockedTo);
                    break;
                } else {
                    //当前仓库锁定失败，重试下一个
                }
            }

            if (!skuLock) {
                //当前商品所有库存都没锁住
                throw new NoStockException(skuId);
            }
        }
        //肯定全部锁定成功
        return true;
    }

    @Transactional
    @Override
    public void unLockedStock(StockLockedTo stockLockedTo) {
        WareOrderTaskDetailEntity detailEntity = taskDetailService.getById(stockLockedTo.getDetail().getId());
        if (detailEntity != null) {
            //解锁库存
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(stockLockedTo.getId());
            //根据orderSn查询订单状态
            R order = orderFeignService.getOrderStatus(taskEntity.getOrderSn());
            if (order.isSuccess()) {
                String data = JSON.toJSONString(order.get("data"));
                OrderVo orderVo = JSON.parseObject(data, new TypeReference<OrderVo>() {
                });
                //2 有订单
                //2.1已取消，解锁库存
                //2.2 没取消，不能解锁库存
                if (orderVo == null || orderVo.getStatus() == 4) {
                    log.warn("收到库存解锁消息,订单不存在或者已经取消，stockLockedTo：{}",stockLockedTo);
                    //1订单不存在，订单服务本身可能已经回滚了，需要解锁库存
                    // 2 已经取消订单，也需解锁库存
                    //判断未解锁才解锁
                    if (detailEntity.getLockStatus() == 1) {
                        StockDetailLockedTo detail = stockLockedTo.getDetail();
                        this.unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detail.getId());
                    }

                }
            } else {
                throw new RuntimeException("order 远程服务调用失败");
            }
        }
    }

    public void unLockStock(Long skuId, Long wareId, Integer skuNum, Long taskDetailId) {
        //更新库存还原
        baseMapper.unLockStock(skuId, wareId, skuNum);
        //更新库存工作单状态
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(taskDetailId);
        //2为已解锁
        detailEntity.setLockStatus(2);
        taskDetailService.updateById(detailEntity);
    }

    @Transactional
    @Override
    public void unLockedStock(OrderTo orderTo) {
        //查询最新的库存解锁状态
        WareOrderTaskEntity entity = wareOrderTaskService.getOrderTaskByOrderSn(orderTo.getOrderSn());
        if (entity != null) {
            //按照库存工作单找到未解锁的库存去解锁
            List<WareOrderTaskDetailEntity> list = taskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", orderTo.getId()).eq("lock_status", 1));
            if (!CollectionUtils.isEmpty(list)) {
                for (WareOrderTaskDetailEntity item : list) {
                    this.unLockStock(item.getSkuId(), item.getWareId(), item.getSkuNum(), item.getId());
                }
            }
        }
    }
}
